package com.water.camera.activity;

import android.content.ClipData;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.viewpager2.widget.ViewPager2;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.plata.base.aclr.common.SilentTask;
import com.plata.base.aclr.common.TaskEngine;
import com.water.camera.App;
import com.water.camera.adapter.PhotoAdapter;
import com.water.camera.bean.MediaData;
import com.water.camera.bean.PageIndex;
import com.water.camera.databinding.ActivityPreviewPhotoBinding;
import com.water.camera.fragment.BaseDialogFragment;
import com.water.camera.fragment.DeleteDlg;
import com.water.camera.fragment.EditTypeDlg;
import com.water.camera.fragment.FileUtilCallback;
import com.water.camera.fragment.VideoFragment;
import com.water.camera.util.ImageUtil;
import com.water.camera.util.Read;
import com.water.camera.util.ToastUtil;
import com.water.camera.util.Utils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class PreviewPhotoAct extends BaseActivity {

    ActivityPreviewPhotoBinding binding;
    PhotoAdapter adapter = null;
    final List<File> list = new ArrayList<>();
    ExoPlayer player = null;
    int mode;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        binding = ActivityPreviewPhotoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        mode = getIntent().getIntExtra("mode", 0);
        binding.includeToolbar.ivBack.setOnClickListener(v -> finish());

        if (Utils.isInstalled("com.tencent.mm")) {
            binding.llShareWx.setVisibility(View.VISIBLE);
        } else {
            binding.llShareWx.setVisibility(View.GONE);
        }
        binding.ivShare.setOnClickListener(v -> {
            loadImg();
        });
        if (mode == 1) {
            binding.includeToolbar.tvRight.setVisibility(View.INVISIBLE);
        }
        binding.includeToolbar.tvRight.setOnClickListener(v -> {
            Intent tmp = new Intent(PreviewPhotoAct.this, BatchPhotoAct.class);
            startActivityForResult(tmp, 10);
        });
        binding.ivDelete.setOnClickListener(v -> delete());
        binding.rlWaterMask.setOnClickListener(v -> {
            if (mode == 1) {
                ToastUtil.showShortToast(this, "只能编辑图片");
                return;
            }
            EditTypeDlg dlg = new EditTypeDlg();
            dlg.setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                @Override
                public void onDismiss(boolean isOk, Object value) {
                    if (isOk) {
                        int i = (Integer) value;
                        if (i == 0) {
                            Intent tmp = new Intent(PreviewPhotoAct.this, EditPhotoAct.class);
                            MediaData data = adapter.getData(binding.rvPreview.getCurrentItem());
                            tmp.putExtra("data", data);
                            startActivityForResult(tmp, 10);
                        } else if (i == 2) {
                            Intent tmp = new Intent(PreviewPhotoAct.this, BatchPhotoAct.class);
                            startActivityForResult(tmp, 10);
                        }
                    }
                }
            });
            dlg.show(getSupportFragmentManager(), "");
        });
        binding.rvPreview.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                if (position >= adapter.getItemCount() - 3 && !loadAll) {
                    loadImages();
                }
                setPlayer();
            }
        });
        loadImages();
    }

    private void setPlayer() {
        Fragment myFragment = getSupportFragmentManager().findFragmentByTag("f" + adapter.getItemId(binding.rvPreview.getCurrentItem()));
        if (myFragment instanceof VideoFragment) {
            ((VideoFragment) myFragment).setPlayer(buildPlayer());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (player != null && player.isPlaying()) {
            player.pause();
        }
    }

    private ExoPlayer buildPlayer() {
        if (player != null) {
            player.release();
        }
        player = new ExoPlayer.Builder(this).build();
        return player;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10) {
            if (resultCode == RESULT_OK) {
                page = 0;
                loadAll = false;
                loadImages();
            }
        }
    }

    int page = 0;
    boolean isLoading = false, loadAll = false;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsg(PageIndex page) {
        this.page = page.page + 1;
    }

    private void loadImages() {
        showLoading();
        if (isLoading) {
            return;
        }
        isLoading = true;
        boolean first = page == 0;
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                List<MediaData> list;
                if (mode == 1) {
                    list = new Read().loadVideo(App.getApp(), page++);
                } else {
                    list = new Read().loadImageData(App.getApp(), page++);
                }
                h.post(() -> {
                    isLoading = false;
                    if (isFinishing() || isDestroyed()) {
                        return;
                    }
                    hideLoading();
                    if (list.isEmpty()) {
                        loadAll = true;
                    }
                    if (adapter == null || first) {
                        adapter = new PhotoAdapter(PreviewPhotoAct.this, list, mode == 1);
                        binding.rvPreview.setAdapter(adapter);
                    } else {
                        adapter.append(list);
                    }
                });
            }
        });
    }

    private void loadImg() {
        if (adapter == null || adapter.getItemCount() == 0) {
            return;
        }
        MediaData data = adapter.getData(binding.rvPreview.getCurrentItem());
        if (mode == 1) {
            File tmp = new File(data.getPath());
            File f = new File(getExternalCacheDir(), "shareData_path/" + tmp.getName());
            showLoading();
            TaskEngine.getInstance().submit(new SilentTask("") {
                @Override
                public void runInBackground() throws Exception {
                    Utils.copy(data.getPath(), f.getAbsolutePath(), false);
                    list.add(f);
                    h.post(() -> {
                        hideLoading();
                        share(f, true);
                    });
                }
            });
            return;
        }
        Glide.with(this).load(data.getPath()).listener(new RequestListener<Drawable>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, @Nullable Object model, @NonNull Target<Drawable> target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(@NonNull Drawable resource, @NonNull Object model, Target<Drawable> target, @NonNull DataSource dataSource, boolean isFirstResource) {
                Bitmap bm = ((BitmapDrawable) resource).getBitmap();
                File f = new File(getExternalCacheDir(), "shareData_path/" + System.currentTimeMillis() + ".jpg");
                Utils.saveImageTo(bm, f.getAbsolutePath());
                list.add(f);
                share(f, false);
                return true;
            }
        }).preload();
    }

    private void share(File f, boolean video) {
        try {
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType(video ? "video/*" : "image/*");
            Uri uri = FileProvider.getUriForFile(this, this.getPackageName(), f);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(Intent.EXTRA_STREAM, uri);
            intent.setClipData(ClipData.newRawUri("", uri));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(Intent.createChooser(intent, "分享"));
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideLoading();
        EventBus.getDefault().unregister(this);
        if (player != null) {
            player.stop();
            player.release();
        }
        for (File f : list) {
            f.delete();
        }
    }

    private void delete() {
        if (adapter == null || adapter.getItemCount() == 0) {
            return;
        }
        DeleteDlg dlg = new DeleteDlg().setMsg(mode == 1 ? "确认将此视频从本机永久删除" : "");
        dlg.setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
            @Override
            public void onDismiss(boolean isOk, Object value) {
                if (isOk) {
                    doDelete();
                }
            }
        });
        dlg.show(getSupportFragmentManager(), "");
    }

    private void doDelete() {
        int i = binding.rvPreview.getCurrentItem();
        String path = adapter.getData(i).getPath();
        if (mode == 1) {
            ImageUtil.INSTANCE.deleteVideoFileUri(this, path, new FileUtilCallback() {

                @Override
                public void onResult(boolean success) {
                    if (success) {
                        adapter.remove(i);
                        h.postDelayed(() -> {
                            if (adapter.getItemCount() == 0) {
                                ToastUtil.showShortToast(App.getApp(), "没有视频");
                            } else if (i < adapter.getItemCount()) {
                                binding.rvPreview.setCurrentItem(i);
                                setPlayer();
                            } else {
                                binding.rvPreview.setCurrentItem(adapter.getItemCount() - 1);
                            }
                        }, 500);
                        ToastUtil.showShortToast(App.getApp(), "已删除");
                    } else {
                        ToastUtil.showShortToast(App.getApp(), "删除失败");
                    }
                }
            });
        } else {
            ImageUtil.INSTANCE.deleteFileUri(this, path, new FileUtilCallback() {

                @Override
                public void onResult(boolean success) {
                    if (success) {
                        adapter.remove(i);
                        ToastUtil.showShortToast(App.getApp(), "已删除");
                    } else {
                        ToastUtil.showShortToast(App.getApp(), "删除失败");
                    }
                }
            });
        }
    }
}
